<script setup lang="ts">
import { invoke } from '@tauri-apps/api/core';
import { open } from '@tauri-apps/plugin-dialog';
import { debounce } from 'lodash';
import { BrowserStorage } from 'my-web-core/storage';
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';

import {
  IconChevronDown,
  IconDeviceFloppy,
  IconLogout,
  IconPinnedFilled,
  IconPlus,
  IconRefresh,
  IconSearch,
  IconUnlink,
} from '@tabler/icons-vue';

import LocaleName from '@/shared/constants/locale-name';
import StorageKey from '@/shared/constants/storage-key';
import SystemTray from '@/shared/services/system-tray';

defineProps<{
  loading: boolean;
}>();

const emit = defineEmits<{
  (e: 'runPinned'): void;
  (e: 'add', path: string): void;
  (e: 'reload'): void;
  (e: 'clearBroken'): void;
  (e: 'save'): void;
  (e: 'keywordChange', keyword: string): void;
}>();

const { t, locale } = useI18n();
const keyword = ref('');
const keywordInputFocused = ref(false);

// Computes locale title for display in the drop down title.
const currentLocaleTitle = computed<string>(() =>
  currentLocale.value == LocaleName.zhCn ? '中文' : 'EN',
);

const onKeywordChange = debounce((val: string) => {
  emit('keywordChange', val);
}, 500);

watch(keyword, onKeywordChange);

// Loads saved locale.
let currentLocale = ref(BrowserStorage.loadLocalData(StorageKey.locale));

/**
 * Changes current locale based on user selection.
 */
function changeLocale(localeParam: string): void {
  currentLocale.value = localeParam;
  locale.value = localeParam;
  BrowserStorage.saveLocalData(StorageKey.locale, localeParam);

  SystemTray.updateMenu({
    exitText: t('exit'),
  });
}

/**
 * Opens file dialog for selection.
 */
async function openDirDialog(): Promise<void> {
  // Opens file dialog and gets selected file path.
  const path = await open();

  if (path) {
    emit('add', path);
  }
}
</script>

<template>
  <div class="toolbar">
    <div class="button-container">
      <el-button-group>
        <el-button :disabled="loading" :icon="IconPinnedFilled" @click="emit('runPinned')">{{
          t('runPinned')
        }}</el-button>
        <el-button :disabled="loading" :icon="IconPlus" @click="openDirDialog">{{
          t('add')
        }}</el-button>
        <el-button :loading :icon="IconRefresh" @click="emit('reload')">{{
          t('reload')
        }}</el-button>
        <el-button :disabled="loading" :icon="IconUnlink" @click="emit('clearBroken')">{{
          t('clearBroken')
        }}</el-button>
        <el-button :disabled="loading" :icon="IconDeviceFloppy" @click="emit('save')">{{
          t('save')
        }}</el-button>
        <el-button :icon="IconLogout" @click="invoke('exit_app')">{{ t('exit') }}</el-button>
      </el-button-group>
    </div>
    <div>
      <el-dropdown>
        <span class="drop-down-title">
          {{ currentLocaleTitle }}
          <el-icon>
            <IconChevronDown />
          </el-icon>
        </span>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="changeLocale(LocaleName.zhCn)">
              <span :class="{ 'selected-menu-item': currentLocale == LocaleName.zhCn }">中文</span>
            </el-dropdown-item>
            <el-dropdown-item @click="changeLocale(LocaleName.en)">
              <span :class="{ 'selected-menu-item': currentLocale == LocaleName.en }">English</span>
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </div>
  <div
    class="keyword-input-container"
    :class="{ 'keyword-input-focused-container': keywordInputFocused }"
  >
    <el-input
      class="keyword-input"
      v-model="keyword"
      :class="{ focused: keywordInputFocused }"
      :prefix-icon="IconSearch"
      @focus="keywordInputFocused = true"
      @blur="keywordInputFocused = false"
      clearable
    />
  </div>
</template>

<style scoped>
.toolbar {
  background-color: #efefef;
  display: flex;
  align-items: center;
  padding-right: 6px;
}

.button-container {
  flex: 1;
}

.drop-down-title {
  font-size: 0.8rem;
  color: #a1a1a3;
}

.selected-menu-item {
  color: #409eff;
}

.keyword-input-container {
  padding: 1px 5px 0px 5px;
  transition: padding 0.3s ease;
}

.keyword-input-focused-container {
  padding-top: 5px;
  padding-bottom: 2px;
}

.keyword-input {
  font-size: 15px;
  height: 20px;
  transition: height 0.3s ease;
}

.keyword-input.focused {
  font-size: 14px;
  height: 30px;
}
</style>
